package com.hiultra.archive.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.SettingUtil;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hiultra.archive.domain.*;
import com.hiultra.archive.domain.vo.ArchiveDesTaskIssuedVo;
import com.hiultra.archive.domain.vo.ArchiveDesTaskReportVo;
import com.hiultra.archive.domain.vo.ArchiveStocktakingTaskIssuedVo;
import com.hiultra.archive.domain.vo.ResultEntity;
import com.hiultra.archive.mapper.*;
import com.hiultra.archive.service.IArchiveDesTaskService;
import com.hiultra.archive.utils.sgsm.SM2Util;
import com.hiultra.archive.utils.tool.ToolUtils;
import com.hiultra.common.constant.BusinessConstants;
import com.hiultra.common.exception.ServiceException;
import com.hiultra.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 销毁任务Service业务层处理
 *
 * @author paidaxing
 * @date 2024-07-23
 */
@Service
public class ArchiveDesTaskServiceImpl implements IArchiveDesTaskService {
    private static final Logger log = LoggerFactory.getLogger(ArchiveDesTaskServiceImpl.class);
    @Autowired
    private ArchiveDesTaskMapper archiveDesTaskMapper;
    @Autowired
    private ArchiveDesMapper archiveDesMapper;
    @Autowired
    private ArchiveDesUserMapper archiveDesUserMapper;
    @Autowired
    private RoomArchiveMapper roomArchiveMapper;
    @Autowired
    private ArcBoxMapper arcBoxMapper;
    @Autowired
    private ArchiveBoxStatusMapper archiveBoxStatusMapper;
    @Value("${priKey}")
    private String priKey;
    @Value("${pubKey}")
    private String pubKey;
    @Value("${urlIp}")
    private String urlIp;

    /**
     * 查询销毁任务
     *
     * @param taskId 销毁任务主键
     * @return 销毁任务
     */
    @Override
    public ArchiveDesTask selectArchiveDesTaskByTaskId(String taskId) {
        return archiveDesTaskMapper.selectArchiveDesTaskByTaskId(taskId);
    }

    /**
     * 查询销毁任务列表
     *
     * @param archiveDesTask 销毁任务
     * @return 销毁任务
     */
    @Override
    public List<ArchiveDesTask> selectArchiveDesTaskList(ArchiveDesTask archiveDesTask) throws JsonProcessingException {

        return archiveDesTaskMapper.selectArchiveDesTaskList(archiveDesTask);
    }

    /**
     * 新增销毁任务
     *
     * @param archiveDesTask 销毁任务
     * @return 结果
     */
    @Override
    public int insertArchiveDesTask(ArchiveDesTask archiveDesTask) {
        archiveDesTask.setCreateTime(DateUtils.getNowDate());
        return archiveDesTaskMapper.insertArchiveDesTask(archiveDesTask);
    }

    /**
     * 修改销毁任务
     *
     * @param archiveDesTask 销毁任务
     * @return 结果
     */
    @Override
    public int updateArchiveDesTask(ArchiveDesTask archiveDesTask) {
        return archiveDesTaskMapper.updateArchiveDesTask(archiveDesTask);
    }

    /**
     * 批量删除销毁任务
     *
     * @param taskIds 需要删除的销毁任务主键
     * @return 结果
     */
    @Override
    public int deleteArchiveDesTaskByTaskIds(String[] taskIds) {
        return archiveDesTaskMapper.deleteArchiveDesTaskByTaskIds(taskIds);
    }

    /**
     * 删除销毁任务信息
     *
     * @param taskId 销毁任务主键
     * @return 结果
     */
    @Override
    public int deleteArchiveDesTaskByTaskId(String taskId) {
        return archiveDesTaskMapper.deleteArchiveDesTaskByTaskId(taskId);
    }

    /**
     * 销毁任务结果上报接口
     *
     * @param archiveDesTask
     * @return
     */
    @Override
    public int archiveDesTaskResultReport(ArchiveDesTask archiveDesTask) throws JsonProcessingException {
        //查询档案任务信息
        ArchiveDesTask desTask = archiveDesTaskMapper.selectArchiveDesTaskbyDesNo(archiveDesTask.getDesNo());
        if (null == desTask) {
            throw new ServiceException("不存在此工单任务，请检查后重试！");
        }
        //判断工单推送状态，如果已经推送了就不能重复推送了
        if (BusinessConstants.END_PUSHSTATUS.equals(desTask.getPushStatus())) {
            throw new ServiceException("工单编号为" + desTask.getDesNo() + "已经提交推送！请检查重试！");
        }
        List<ArchiveDesTaskReportVo.ArchiveUserInfo> archiveUserInfos = new ArrayList<>();
        //销毁用户信息和档案信息
        List<ArchiveDesUser> archiveDesUserList = archiveDesUserMapper.selectArchiveDesUserList(new ArchiveDesUser() {{
            setTaskId(desTask.getTaskId());
        }});
        for (ArchiveDesUser archiveDesUser : archiveDesUserList) {
            ArchiveDesTaskReportVo.ArchiveUserInfo archiveUserInfo = ToolUtils.convertEntity(archiveDesUser, ArchiveDesTaskReportVo.ArchiveUserInfo::new);
            //todo 转换时间
            //处理时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

            if (ObjectUtil.isNotNull(archiveDesUser.getCanceTime())) {
                archiveUserInfo.setCanceTime(dateFormat.format(archiveDesUser.getCanceTime()));
            }
            if (ObjectUtil.isNotNull(archiveDesUser.getDesTime())) {
                archiveUserInfo.setDesTime(dateFormat.format(archiveDesUser.getDesTime()));
            }
            List<ArchiveDes> archiveDesList = archiveDesMapper.selectArchiveDesList(new ArchiveDes() {{
                setTaskId(desTask.getTaskId());
            }});

            //转化
            List<ArchiveDesTaskReportVo.DesArchive> desArchives = ToolUtils.copyList(archiveDesList, ArchiveDesTaskReportVo.DesArchive::new);
            archiveUserInfo.setDesArchiveList(desArchives);
            archiveUserInfos.add(archiveUserInfo);
        }

        ArchiveDesTaskReportVo archiveDesTaskReportVo = ToolUtils.convertEntity(desTask, ArchiveDesTaskReportVo::new);
        archiveDesTaskReportVo.setArchiveUserInfoList(archiveUserInfos);

        // 将JsonData对象转换为JSON字符串
        String jsonString = new ObjectMapper().writeValueAsString(archiveDesTaskReportVo);
        System.out.println(jsonString);

//         发送请求获取数据
        HashMap hashMap = ToolUtils.sendPostRequest("D0011", urlIp, "", "档案销毁任务上报结果", jsonString, pubKey, priKey);
//
//        //判断是否成功
//        if (hashMap == null || !hashMap.containsKey("code") || !hashMap.get("code").equals("00000")) {
//            System.out.println("档案借阅任务上传结果失败");
//            throw new ServiceException(hashMap.get("message").toString());
//        }
//        System.out.println("档案借阅任务上报结果成功");
//        archiveDesTask.setPushStatus(BusinessConstants.END_PUSHSTATUS);
        return updateArchiveDesTask(archiveDesTask);
    }

    /**
     * 档案销毁任务下发接口
     *
     * @param data
     * @return 结果
     */
    @Override
    public ResultEntity insertIssuedArchiveDesTask(String data) {

        System.out.println("档案销毁任务下发：" + data);
        String decryptedResult = new SM2Util().decryptBySM2(data, priKey);
        System.out.println("档案销毁任务下发解密结果：" + decryptedResult);
        ArchiveDesTaskIssuedVo archiveDesTaskIssuedVo = JSON.parseObject(decryptedResult.trim(), ArchiveDesTaskIssuedVo.class);
        if (ObjectUtil.isNull(archiveDesTaskIssuedVo)) {
            // 返回错误信息或抛出异常
            log.info("入参解析出错，请检查重试");
            return ResultEntity.error("入参解析出错，请检查重试");
        }
        try {
            processArchiveDesTask(archiveDesTaskIssuedVo);
        } catch (ServiceException e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
        return ResultEntity.success();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void processArchiveDesTask(ArchiveDesTaskIssuedVo archiveDesTaskIssuedVo) throws ServiceException {
        try {
            ArchiveDesTask archiveDesTask = ToolUtils.convertEntity(archiveDesTaskIssuedVo, ArchiveDesTask::new);

            ArchiveDesTask archiveDesTask1 = archiveDesTaskMapper.selectArchiveDesTaskbyDesNo(archiveDesTask.getDesNo());
            if (null == archiveDesTask1) {
                archiveDesTask.setTaskId(java.util.UUID.randomUUID().toString().replace("-", ""));
                archiveDesTask.setPushStatus(BusinessConstants.PUSHSTATUS);
                archiveDesTask.setStatus(BusinessConstants.DES_STATUS);

                insertArchiveDesTask(archiveDesTask);
                //处理档案信息
                for (ArchiveDesTaskIssuedVo.DesArchive desArchive : archiveDesTaskIssuedVo.getDesArchiveList()) {
                    ArchiveDes archiveDes = ToolUtils.convertEntity(desArchive, ArchiveDes::new);

                    //查询销毁档案
                    RoomArchive roomArchive = roomArchiveMapper.selectRoomArchiveById(desArchive.getDesArchiveId());
                    //判空
                    if (ObjectUtil.isNull(roomArchive)) {
                        log.info("不存在档案标识" + desArchive.getDesArchiveId() + "，请检查后重试！");
                        throw new ServiceException("不存在档案标识" + desArchive.getDesArchiveId() + "，请检查后重试！");
                    }
                    //如果下发状态为销毁，则更改状态
//                    if (desArchive.getDesStatus().equals(BusinessConstants.DES_STATUS)) {
//                        roomArchiveMapper.updateRoomArchiveDelflag(archiveDes.getDesArchiveId());
//                        //记录档案盒销毁
//                        //记录档案盒状态
//                        ArcBox arcBox = arcBoxMapper.selectArcBoxByBoxCode(roomArchive.getBoxNo());
//                        //判空
//                        if (ObjectUtil.isNull(arcBox)) {
//                            log.info("不存在档案盒标识" + roomArchive.getBoxNo() + "，请检查后重试！");
//                            throw new ServiceException("不存在档案盒标识" + roomArchive.getBoxNo() + "，请检查后重试！");
//                        }
//
//                        ArchiveBoxStatus archiveBoxStatus = new ArchiveBoxStatus();
//                        archiveBoxStatus.setAreaNo(arcBox.getAreaNo());
//                        archiveBoxStatus.setCabinetNo(arcBox.getCabinetNo());
//                        archiveBoxStatus.setBoxBarCode(arcBox.getBoxRfid());
//                        archiveBoxStatus.setBoxNo(arcBox.getBoxCode());
//                        archiveBoxStatus.setHouseLocationNo(arcBox.getHouseLocationNo());
//
//                        archiveBoxStatus.setBoxStatus(BusinessConstants.ARC_DES);
//                        archiveBoxStatus.setRecordTime(DateUtils.getNowDate());
//                        archiveBoxStatus.setPushStatus(BusinessConstants.PUSHSTATUS);
//                        archiveBoxStatusMapper.insertArchiveBoxStatus(archiveBoxStatus);
//
//                    }
                    //把查询到的档案信息赋值给档案销毁信息
                    archiveDes.setArchiveName(roomArchive.getArchiveName());
                    archiveDes.setArchiveType(roomArchive.getArchiveType());
                    archiveDes.setArchObjNo(roomArchive.getArchObjNo());
                    archiveDes.setArchObjType(roomArchive.getArchObjType());
                    archiveDes.setArchObjName(roomArchive.getArchObjName());
                    archiveDes.setAreaNo(roomArchive.getAreaNo());
                    archiveDes.setBoxNo(roomArchive.getBoxNo());
                    archiveDes.setSaveDate(roomArchive.getSaveDate());
                    archiveDes.setCabinetNo(roomArchive.getCabinetNo());
                    archiveDes.setConLevel(roomArchive.getConLevel());
                    archiveDes.setMedForm(roomArchive.getMedForm());
                    archiveDes.setMeansType(roomArchive.getMeansType());
                    archiveDes.setTaskId(archiveDesTask.getTaskId());
                    archiveDes.setLocalStatus(BusinessConstants.DES_STATUS);
                    //处理销户时间
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    //判断时间是否为空
                    if (StrUtil.isEmpty(desArchive.getCanceTime())) {
                        throw new ServiceException("销户时间为空，请检查后重试！");
                    }
                    archiveDes.setCanceTime(sdf.parse(desArchive.getCanceTime()));
                    if (ObjectUtil.isNull(archiveDes.getTaskId())) {
                        archiveDes.setTaskId(archiveDesTask.getTaskId());
                    }
                    if (ObjectUtil.isNull(archiveDes.getId())) {
                        archiveDes.setId(java.util.UUID.randomUUID().toString().replace("-", ""));
                    }
                    archiveDesMapper.insertArchiveDes(archiveDes);
                }
            }
        } catch (ServiceException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new ServiceException(e.getMessage());
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new ServiceException("发生未知异常，事务已回滚");
        }
    }

    /**
     * 销毁任务结果上报接口
     *
     * @return
     */
    @Override
    public ResultEntity timingArchiveDesTaskResultReport() {
        List<ArchiveDesTask> archiveDesTaskList = archiveDesTaskMapper.selectArchiveDesTaskList(new ArchiveDesTask() {{
            setPushStatus(BusinessConstants.PUSHSTATUS);
        }});
        if (archiveDesTaskList.size() > 0) {
            for (ArchiveDesTask archiveDesTask : archiveDesTaskList) {
                try {
                    archiveDesTaskResultReport(archiveDesTask);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
        }
        return ResultEntity.success();
    }
}
